package code.google.gui.fragments.player;

import org.teleal.cling.model.meta.Device;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import code.google.controller.upnp.UpnpController;
import code.google.gui.fragments.RegistrateableFragment;
import code.google.gui.fragments.player.util.DeviceDisplay;
import code.google.gui.interfaces.IUpnpFragment;

import com.example.metamusicgui.R;

/**
 * 
 * @author Fabi
 * 
 */
public class UpnpFragment extends RegistrateableFragment implements
		IUpnpFragment {
	private UpnpController controller;
	private ArrayAdapter<DeviceDisplay> listAdapter;



	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.upnp_listview, container,
				false);
		listAdapter = new ArrayAdapter<DeviceDisplay>(
				getActivity(), android.R.layout.simple_list_item_1);
		ListView deviceList = (ListView) rootView.findViewById(R.id.my_listview);
		deviceList.setAdapter(listAdapter);

		
		Button refresh = (Button) rootView.findViewById(R.id.upnp_refresh);
		refresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				controller.refreshList();
				System.out.println("Refreshing");
			}
		});
		return rootView;
	}

	@Override
	public void registrateFragmentAt(Activity context) {
		controller = new UpnpController(this);
		controller.refreshList();
	}

	@Override
	public void deregistrateFragmentFrom(Activity context) {
		// TODO Auto-generated method stub

	}

	@Override
	public void addToList(Device device) {
		new UpdateUiClass().execute(device);
	}

	@Override
	public void removeFromList(Device device) {
		// TODO Auto-generated method stub

	}
	
	private class UpdateUiClass extends AsyncTask<Device, Void, DeviceDisplay> {

		@Override
		protected DeviceDisplay doInBackground(Device... params) {
			return new DeviceDisplay(params[0]);
		}
		
		protected void onPostExecute(DeviceDisplay display){
			if(listAdapter != null){
				listAdapter.add(display);
			}
		}
	}
}
